﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using NETCore.Auth.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;

namespace Auth.Classic.Filters
{
    public class MyActionAuthrizaFilterAttribute : Attribute, IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {
            // 
        }

        /// <summary>
        /// 进入Action前的操作
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuting(ActionExecutingContext context)
        {
            //Console.WriteLine(context.HttpContext.Request.QueryString);
            //Console.WriteLine(context.HttpContext.Response.Headers.ContainsKey("LoginType"));
            //Console.WriteLine(context.HttpContext.Request.Headers.ContainsKey("LoginType"));
            Console.WriteLine("开始验证权限...");

            if (!context.HttpContext.Request.Cookies.TryGetValue("LoginType", out string loginType))
            {
                context.Result = new JsonResult(new
                {
                    Success = false,
                    Message = "没有权限"
                });
                context.Result = new RedirectResult("/Account/Login");
                return;
            }

            string sUser;
            if (loginType == "cookie")
            {
                // 从cookie中获取用户信息
                context.HttpContext.Request.Cookies.TryGetValue("CurrentUser", out sUser);
            }
            else
            {
                // 从session中获取用户信息
                sUser = context.HttpContext.Session.GetString("CurrentUser");
            }

            //CurrentUser currentUser = JsonSerializer.Deserialize<CurrentUser>(sUser);

            // 获取请求头
            string header = context.HttpContext.Request.Headers["X-Requested-With"];
            // 是否ajax请求
            bool isAjaxRequest = "XMLHttpRequest".Equals(header);

            if (string.IsNullOrEmpty(sUser))
            {
                Console.WriteLine("没有权限...");
                if (isAjaxRequest)
                {
                    context.Result = new JsonResult(new
                    {
                        Success = false,
                        Message = "没有权限"
                    });
                }
                context.Result = new RedirectResult("/Account/Login");
                return;
            }
            Console.WriteLine("权限验证成功...");
        }
    }
}
